import java.util.Scanner;
import java.io.*;

/**
 * @author Team 29
 * This class is responsible for loading and saving the users and all their data,
 * as well as processing client commands relating to storing and retrieving user data.
 *
 */
public class DatabaseUsers {
	private static User[] users = loadUsers();
	private static int nextslot;
	public DatabaseUsers(){
		users[0] = new User("Sun","Tzu","0", "sysadmin");
		users[0].setLoginName("admin");
		users[0].setLoginPassword("password");
		
		users[1] = new User("George","Orwell","1", "patient");
		users[1].setLoginName("patient");
		users[1].setLoginPassword("password2");
		
		users[2] = new User("Augustus","Caesar","2", "nurse");
		users[2].setLoginName("nurse");
		users[2].setLoginPassword("password3");
		
		users[3] = new User("Victor","Frankenstein","3", "doctor");
		users[3].setLoginName("doctor");
		users[3].setLoginPassword("password4");
		
	}//end disableusers
	
	/**
	 * @param s1
	 * @param s2
	 * @return
	 * Checks if provided login credentials are valid, 
	 * sends the appropriate response back.
	 */
	public static String loginAttempt(String s1, String s2)
	{
		int c = 0; 
		for(int a = 0; a < nextslot; a++)
		{
			if(users[a] != null && users[a].getLoginName().equals(s1))
			{
				if(	users[a].getLoginPassword().equals(s2))
				{
				if(users[a].patienttype.equals("patient"))
				c = 0;
				if(users[a].patienttype.equals("nurse"))
				c = 1;
				if(users[a].patienttype.equals("doctor"))
				c=2;
				if(users[a].patienttype.equals("sysadmin"))
				c = 3;
				
				users[a].unfail();
				return "" + a + " " + c;
				}
				else
				users[a].fail();
			}
				
		}
		
		return "-1";
	}//end loginattempt
	
	/**
	 * @param s1
	 * @param s2
	 * @param s3
	 * @param s4
	 * @param s5
	 * @param s6
	 * @return
	 * Adds a new user into the system.
	 */
	public static String addUser(String s1, String s2, String s3, String s4, String s5,
			String s6)
	{
		for(int a = 0; a<nextslot; a++)
		{
			if(users[a] != null && users[a].getLoginName().equals(s1))
				return "-1";
		}
		if(s6.equals("0"))
		users[nextslot] = new User(s3,s4,"" + nextslot, "patient");
		if(s6.equals("1"))
		users[nextslot] = new User(s3,s4,"" + nextslot, "nurse");
		if(s6.equals("2"))
		users[nextslot] = new User(s3,s4,"" + nextslot, "doctor");
		if(s6.equals("3"))
		users[nextslot] = new User(s3,s4,"" + nextslot, "sysadmin");	
		
		users[nextslot].setLoginName(s1);
		users[nextslot].setLoginPassword(s2);
		users[nextslot].contactinfo = s5;
		nextslot++;
		return "" + (nextslot-1);
	}//end adduser
	
	/**
	 * @param s1
	 * @param s2
	 * @param s3
	 * @param s4
	 * @param s5
	 * @param s6
	 * @param s7
	 * @return
	 * Changes the user's instance data as necessary.
	 */
	public static String editUser(String s1, String s2, String s3, String s4, 
			String s5, String s6, String s7)
	{
		int a = Integer.valueOf(s1);
		users[a].bi.setFullName(s2 + " " + s3);
		users[a].bi.setDateOfBirth(s4);
		users[a].bi.setAge(s5);
		users[a].bi.setHeight(s6);
		users[a].bi.setWeight(s7);
		return "0";
	}//end edituser
	
	/**
	 * @param s1
	 * @param s2
	 * @return
	 * changes the user's privilege level.
	 */
	public static String editPrivilege(String s1, String s2)
	{
		users[Integer.valueOf(s1)].patienttype = s2;
		return "0";
	}
	
	public static String retrieveInfo(String s1)
	{
		int a = Integer.valueOf(s1);
		String r = users[a].bi.fullName + " " +
		users[a].bi.getDateOfBirth() + " " +
		users[a].bi.getAge() + " " + 
		users[a].bi.getHeight() + " " +
		users[a].bi.getWeight();
		return r;
	}
	public static User getUser(int a)
	{
		return users[a];
	}
	public static String getStats()
	{
		int a = 0;
		for(int b = 0; b < nextslot; b++)
		{
			if(users[b] != null && users[b].patienttype.equals("patient"))
				a++;
		}
		return "Total number of patients: " + a;
	}
	public static String retrieveMedHist(String s1)
	{
		return users[Integer.valueOf(s1)].mh.getMedicalHistory();
	}
	public static String setMedHist(String s1, String s2)
	{
		users[Integer.valueOf(s1)].mh.setMedicalHistory(s2);
		return "0";
	}
	public static String retrieveTrtRec(String s1)
	{
		return users[Integer.valueOf(s1)].tr.getTreatmentRecord();
	}
	public static String setTrtRec(String s1, String s2)
	{
		users[Integer.valueOf(s1)].tr.setTreatmentRecord(s2);
		return "0";
	}
	public static String retrieveDocOrd(String s1)
	{
		return users[Integer.valueOf(s1)].docord.toString();
	}
	public static String setDocOrd(String s1, String s2, String s3, String s4, String s5)
	{
		users[Integer.valueOf(s1)].docord.setPrescription(s2);
		users[Integer.valueOf(s1)].docord.setLabWork(s3);
		users[Integer.valueOf(s1)].docord.setFollowUpInstructions(s4);
		users[Integer.valueOf(s1)].docord.setOtherInstructions(s5);
		return "0";
	}
	public static String setPass(String s1, String s2)
	{
		users[Integer.valueOf(s1)].setLoginPassword(s2);
		return "0";
	}
	public static String resetPass(String s1)
	{
		users[Integer.valueOf(s1)].setLoginPassword("temppassword");
		return "temppassword";
	}
	
	public static String retrieveBillingInfo(String s1)
	{
		String r = users[Integer.valueOf(s1)].bill.billingAddress + " " + 
		users[Integer.valueOf(s1)].bill.creditCardNo;
		return r;
	}
	public static String editBillingInfo(String s1, String s2, String s3)
	{
		users[Integer.valueOf(s1)].bill.billingAddress = s2;
		users[Integer.valueOf(s1)].bill.creditCardNo = s3;
		return "0";
	}
	public static String retrieveInvoice(String s1)
	{
		String r = users[Integer.valueOf(s1)].invo.reason + " " +
		users[Integer.valueOf(s1)].invo.price;
		return r;
	}
	public static String editInvoice(String s1, String s2, String s3)
	{
		users[Integer.valueOf(s1)].invo.reason = s2;
		users[Integer.valueOf(s1)].invo.price = s3;
		return "0";
	}
	public static String suspendAccount(String s1)
	{
		users[Integer.valueOf(s1)].fail();
		users[Integer.valueOf(s1)].fail();
		users[Integer.valueOf(s1)].fail();
		return "0";
	}
	public static String unsuspendAccount(String s1)
	{
		users[Integer.valueOf(s1)].unfail();
		return "0";
	}
	public static String deleteAccount(String s1)
	{
		users[Integer.valueOf(s1)] = null;
		return "0";
	}
	/**
	 * @return
	 * Sends the all of the users indeces and login credentials in a single string.
	 */
	public static String sendUsers()
	{
		String r = "";
		for(int a = 0; a < nextslot; a++)
		{
			if(users[a]!=null)
				r =r + " " + a + "_" + users[a].loginName + "_" + users[a].loginPassword;
		}
		return r;
	}
	/**
	 * @return
	 * loads users from disk.
	 */
	public static User[] loadUsers(){
		Scanner reader;
		try{
			reader = new Scanner(new File("src/users.txt"));
		}
		catch(Exception e){
			System.out.println("Unable to load user file");
			Logger.log("Unable to load user file");
			return new User[50];
		}
		String s="";
		while (reader.hasNextLine()){
			s+=reader.nextLine()+"\r\n";
		}
		
		String[] userList = s.split("\r\n\r\n");
		User[] users = new User[50];
		for (int i=0; i<userList.length-1; i++){
			try{
				if (userList[i].compareTo("EMPTY")!=0) users[i]=User.fromString(userList[i]);
			}
			catch(Exception e){
				System.out.println("Error parsing user: " + userList[i]);
				Logger.log("Error parsing user: " + userList[i]);
			}
		}
		try{
			nextslot=Integer.parseInt(userList[userList.length-1]);
		}
		catch(Exception e){
			nextslot=0;
			System.out.println("nextslot parse failed");
			Logger.log("nextslot parse failed");
		}
		return users;
	}
	/**
	 * saves users to disk.
	 */
	public static void saveUsers(){
		FileWriter writer;
		try{
			writer = new FileWriter(new File("src/users.txt"));
		}
		catch(Exception e){
			System.out.println("Error opening file to write.");
			Logger.log("Error opening file to write.");
			return;
		}
		try {
			for (int i=0; i<users.length; i++){
				if (users[i]!=null) writer.write(users[i].toSaveString()+"\r\n\r\n");
				else writer.write("EMPTY\r\n\r\n");
			}
			writer.write(""+nextslot+"\r\n\r\n");
			writer.close();
		} 
		catch (IOException e) {
			System.out.println("Error writing to user file");
			Logger.log("Error writing to user file");
		}
	}
}//end class
